package com.j3.db.io;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import com.j3.converter.MyDateConvertor;
import com.j3.sql.GridUtils;
import com.j3.string.StringUtils;

public class RowEntity {

    static {
        ConvertUtils.register(new MyDateConvertor(null), Date.class);
    }

    public <T> List<T> load(GridUtils gridbean, Class<T> clazz) throws InstantiationException, IllegalAccessException {
        List<T> rows = new ArrayList<T>();
        while (gridbean.next()) {
            T row = clazz.newInstance();
            update(gridbean, row);
            rows.add(row);
        }
        return rows;
    }

    public void update(GridUtils gridbean, Object entity) {
        String[] columns = gridbean.getColumns();
        for (int i = 0; i < columns.length; i++) {
            String name = columns[i];
            if ("".equals(gridbean.get(name))) {
                continue;
            }

            try {
                BeanUtils.copyProperty(entity, StringUtils.underlineToCapitalize(name), gridbean.get(name));
            }
            catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

}